package com.example.demo.service;

import com.example.demo.dto.DeepSeekRequest;
import com.example.demo.dto.DeepSeekResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class DeepSeekService {

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekService.class);

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Value("${deepseek.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate;

    public DeepSeekService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public String chat(String message) {
        try {
            // 1. 构建请求体
            DeepSeekRequest request = new DeepSeekRequest();
            request.setModel("deepseek-chat");
            request.addMessage("user", message);

            // 2. 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiKey);
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<DeepSeekRequest> requestEntity = new HttpEntity<>(request, headers);

            // 3. 发送请求并记录日志
            logger.info("Sending request to DeepSeek API: URL={}, Body={}", apiUrl, request);

            ResponseEntity<DeepSeekResponse> responseEntity = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    DeepSeekResponse.class
            );

            // 4. 处理响应
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                DeepSeekResponse response = responseEntity.getBody();
                if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) {
                    return response.getChoices().get(0).getMessage().getContent();
                }
            }
            throw new RuntimeException("API响应异常，状态码：" + responseEntity.getStatusCode());
        } catch (Exception e) {
            logger.error("调用DeepSeek API失败: URL={}, Error={}", apiUrl, e.getMessage(), e);
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        }
    }
}